package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qili.entity.supervisor.ProjectContract;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.sys.SysUser;
import com.qili.service.SysUserService;
import com.qili.service.supervisor.ProjectContractService;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.service.supervisor.SupervisorProjectFormsDataService;
import com.qili.service.supervisor.SupervisorProjectFormsService;
import com.qili.util.SpringUtil;
import com.qili.util.StringUtil;
import com.qili.util.WordUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author zhaoyongke
 * @date 2021/10/8
 * @description
 */
@Log
public class DhysJob  implements Job {

    @Autowired
    SupervisorFileService  supervisorFileService;

    @Autowired
    SupervisorProjectFormsDataService  supervisorProjectFormsDataService;

    @Autowired
    SupervisorProjectFormsService   supervisorProjectFormsService;

    @Autowired
    ProjectContractService  projectContractService;




    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("JobDemo1：启动任务=======================");
        run();
        System.out.println("JobDemo1：下次执行时间====="+
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime())+"==============");
    }

    public void run(){
        // 查询 货物清单
        //

        Example examplefile = new Example(SupervisorFile.class);

        Example.Criteria criteriaquery = examplefile.createCriteria();
        criteriaquery.andLike("fileName", "%货物清单%");
        List<SupervisorFile> lists = supervisorFileService.selectByExample(examplefile);
        if(lists.size()>100){
            return ;
        }
        for (int i = 0; i < lists.size(); i++) {

            SupervisorFile filedc = lists.get(i);
            String pcId = filedc.getPcId();
            Example example = new Example(SupervisorProjectForms.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spfPrjid", filedc.getProjectId());
            if(StringUtil.isNotBlank(pcId)){
                ProjectContract contract = projectContractService.selectByPrimaryKey(pcId);
                if(contract!=null){
                    String  fbcode = contract.getCode();
                    //  criteria.andEqualTo("fbCode", fbcode);
                }
            }
            criteria.andEqualTo("pcId", pcId);
            criteria.andEqualTo("spfMilid", filedc.getSpmId());
            criteria.andLike("saveFilePath", "%货物清单%");
            List<SupervisorProjectForms> listsfrom = supervisorProjectFormsService.selectByExample(example);
            for (SupervisorProjectForms forms : listsfrom) {
                SupervisorProjectFormsData data = new SupervisorProjectFormsData();
                data.setSpfId(forms.getSpfId());
                supervisorProjectFormsDataService.delete(data);
                supervisorProjectFormsService.deleteByPrimaryKey(forms.getSpfId());
            }

        }
        for (int i = 0; i < lists.size(); i++) {
            try {
                SupervisorFile filedc = lists.get(i);
                String pcId = filedc.getPcId();
                // 重新解析
                String url = filedc.getUrl();
                File filewj=new File(url);
                if(filewj.exists()){
                    String AsFormId = IdUtil.simpleUUID();
                    SupervisorProjectDTO  pDto=new SupervisorProjectDTO();
                    pDto.setId(filedc.getProjectId());
                    pDto.setStageId(filedc.getStageId());
                    pDto.setSpmId(filedc.getSpmId());
                    pDto.setFbId(filedc.getPcId());
                    parsingFileDataToForm(url, pDto, AsFormId);
                    int AiTableIndex = 1;
                    List<List<String>> checkGs = WordUtil.getWordTableData(url, AiTableIndex, 1);
                    int size = checkGs.size();
                    int y = 0;
                    for (List<String> rowdata : checkGs) {
                        if (i == 0) {
                            //序号
                            String xh = rowdata.get(0) + "";
                            //区域
                            String qy = rowdata.get(1) + "";
                            if (!"序号".equals(xh) || !"区域".equals(qy)) {
                                throw new RuntimeException("请按照模板格式导入");
                            }
                            break;
                        }
                        y++;
                    }

                    // 获取 货物清单表格中的数据
                    List<List<String>> AlstTableData = WordUtil.getWordTableData(url, AiTableIndex, 2);
                    if(AlstTableData!=null){
                        if(AlstTableData.size()>0){
                            for (int j = 0; j <AlstTableData.size() ; j++) {
                                String str = AlstTableData.get(j)+"";
                                if(StringUtil.isNotBlank(str)){
                                    if(str.indexOf("填表说明")>0){
                                        AlstTableData.remove(j);
                                    }
                                }
                            }
                        }

                    }

                    int AiRowCnt = AlstTableData.size();
                    // 将解析的表格数据保存到fromdata 表中
                    for (List<String> rowdata : AlstTableData) {
                        parsingFileDataToFormData(AiTableIndex, AsFormId, AiRowCnt, rowdata);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }




    }

    private void parsingFileDataToForm(String psFileName, SupervisorProjectDTO dto, String asFormId) {
        //给Form表增加实例
        SupervisorProjectForms AoForms = new SupervisorProjectForms();
        String fbId= dto.getFbId();
        String  fbcode="";
        if(StringUtil.isNotBlank(fbId)){
            ProjectContract contract = projectContractService.selectByPrimaryKey(fbId);
            if(contract!=null){
                fbcode = contract.getCode();
            }
            AoForms.setFbCode(fbcode);
        }else{
            AoForms.setFbCode(dto.getFbCode());
        }
        AoForms.setSpfId(asFormId);
        AoForms.setSpfPrjid(dto.getId());
        AoForms.setSpfStaid(dto.getStageId());

        AoForms.setSpfMilid(dto.getSpmId());

        AoForms.setPcId(dto.getFbId());
        AoForms.setSaveFilePath(psFileName);
        supervisorProjectFormsService.insertSelective(AoForms);
    }

    private void parsingFileDataToFormData(int aiTableIndex, String asFormId, int aiRowCnt, List<String> rowdata) {
        int AiColCnt = rowdata.size();
        JSONObject AjsItem = new JSONObject();
        for (int i = 0; i < AiColCnt; i++) {
            AjsItem.put("Data" + (i + 1), rowdata.get(i));
        }
        SupervisorProjectFormsData supervisorProjectFormsData = JSONObject.toJavaObject(AjsItem, SupervisorProjectFormsData.class);
        supervisorProjectFormsData.setSpfId(asFormId);
        supervisorProjectFormsData.setTableIndex(aiTableIndex);
        supervisorProjectFormsData.setTableRow(aiRowCnt);
        supervisorProjectFormsData.setTableCos(AiColCnt);
        supervisorProjectFormsDataService.insertSelective(supervisorProjectFormsData);
    }

}
